package com.jzo2o.orders.manager.listener;

import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 订单自动取消业务 消息监听者
 *
 * @Author mr.lin
 * @Date 2025/2/7 14:26
 */
@Slf4j
@Component
public class OrderCancelListener {

    @Autowired
    private IOrdersCreateService ordersCreateService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = MqConstants.Queues.ORDERS_CANCEL_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.ORDERS, type = ExchangeTypes.TOPIC, delayed = "true"),
            key = MqConstants.RoutingKeys.ORDERS_CANCEL_KEY))
    public void bathCancelOrders(String msg) {
        //1.判断消息是否存在
        if (msg == null) {
            return;
        }
        //2.将消息转换为订单id后,判断是否有这个订单
        Long orderId = Long.valueOf(msg);
        Orders orders = ordersCreateService.getById(orderId);
        if (orders == null) {
            return;
        }
        //3.判断订单状态是否是未支付
        if (orders.getOrdersStatus().equals(OrderStatusEnum.NO_PAY.getStatus())) {
            return;
        }
        //4.修改订单状态为 已取消 并且在订单取消表添加一条数据
        ordersCreateService.cancelNoPayUpdate(orderId, "订单超时自动取消", true);
        log.info("[订单状态变更]订单超时自动取消状态变更完毕>>>>>>");
    }
}
